//
//  PlateManager.m
//  PlateDemo
//
//  Created by ocrgroup on 2021/3/5.
//  Copyright © 2021 ocrgroup. All rights reserved.
//

#import "PlateManager.h"
#import <SPlate/SPlate.h>

@interface PlateManager () <PlateCameraDelegate>

@property (nonatomic, strong) SPlate * sPlate;

@end


@implementation PlateManager

static id _instacetype;

/**
 单例全局访问点
 
 @return 对象实例
 */
+ (instancetype)sharedManager {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSLog(@"BundleID:%@",[[NSBundle mainBundle] bundleIdentifier]);
        _instacetype = [[super alloc] init];
    });
    return _instacetype;
}

/**
 拍照/导入识别
 
 @param plateImage 需要识别的图像
 @param authCode 授权文件名
 */
- (void)recognizePlateWithPhoto:(UIImage *)plateImage andAuthCode:(NSString *)authCode {
    NSLog(@"SDK版本号：%@", self.sdkVersion);
    //激活核心
    int success = [self initRecognizeCoreWithAuthCode:authCode];
    if (success != 0) {
        //激活失败
        if ([self.delegate respondsToSelector:@selector(platePhotoRecognizeFinishWithResult:plateColor:srcImage:plateImage:andErrorCode:)]) {
            [self.delegate platePhotoRecognizeFinishWithResult:@"" plateColor:@"" srcImage:plateImage plateImage:plateImage andErrorCode:success];
        } else {
            NSLog(@"代理方法platePhotoRecognizeFinishWithResult:plateColor:srcImage:plateImage:andErrorCode:未实现");
        }
        return ;
    }
    
    plateImage = [self fixOrientation:plateImage];
    
    int bSuccess = [self.sPlate recognizeSPlateImageDeep:plateImage];
    
    if ([self.delegate respondsToSelector:@selector(platePhotoRecognizeFinishWithResult:plateColor:srcImage:plateImage:andErrorCode:)]) {
        [self.delegate platePhotoRecognizeFinishWithResult:self.sPlate.nsPlateNo plateColor:self.sPlate.nsPlateColor srcImage:plateImage plateImage:self.sPlate.plateImg andErrorCode:bSuccess];
    } else {
        NSLog(@"代理方法platePhotoRecognizeFinishWithResult:plateColor:srcImage:plateImage:andErrorCode:未实现");
    }
    
    //释放核心
    [self.sPlate freeSPlate];
}



//MARK:视频流预览识别
- (void)recognizePlateByVideoStreamWithController:(UIViewController *)parentController usePush:(BOOL)usePush isHorizontalRecognize:(BOOL)isHorizontalRecognize andAuthCode:(NSString *)authCode {
    PlateCameraController * cameraVC = [[PlateCameraController alloc] initWithAuthorizationCode:authCode];
    cameraVC.delegate = self;
    cameraVC.isHorizontalRecognize = isHorizontalRecognize;
    cameraVC.deviceDirection = parentController.preferredInterfaceOrientationForPresentation;
    
    if (usePush) {
        [parentController.navigationController pushViewController:cameraVC animated:YES];
    } else {
        cameraVC.modalPresentationStyle = UIModalPresentationFullScreen;
        [parentController presentViewController:cameraVC animated:YES completion:nil];
    }
}

//MARK:视频流识别回调
- (void)cameraController:(UIViewController *)cameraController recognizePlateSuccessWithResult:(NSString *)plateStr plateColor:(NSString *)plateColor plateImage:(UIImage *)plateImage squareImage:(UIImage *)squareImage andFullImage:(UIImage *)fullImage {
    if ([self.delegate respondsToSelector:@selector(cameraController:videoStreamRecognizePlateFinishWithResult:plateColor:srcImage:areaCutImage:andPlateImage:)]) {
        [self.delegate cameraController:cameraController videoStreamRecognizePlateFinishWithResult:plateStr plateColor:plateColor srcImage:fullImage areaCutImage:squareImage andPlateImage:plateImage];
    } else {
        NSLog(@"代理方法cameraController:videoStreamRecognizePlateFinishWithResult:plateColor:srcImage:areaCutImage:andPlateImage:未实现");
    }
}


//MARK:初始化识别核心
- (int)initRecognizeCoreWithAuthCode:(NSString *)authCode {
    int nRet = [self.sPlate initSPlate:authCode nsReserve:@""];
    if (nRet != 0) {
        NSString *initStr = [NSString stringWithFormat:@"Init Error!Error code:%d",nRet];
        if (nRet == 22) {
            initStr = [initStr stringByAppendingString:@"(Can't find lic)"];
        } else if (nRet == 24) {
            initStr = [initStr stringByAppendingString:@"(BundleID error)"];
        } else if (nRet == 25) {
            initStr = [initStr stringByAppendingString:@"(Out of date)"];
        } else if (nRet == 30) {
            initStr = [initStr stringByAppendingString:@"(SDK Version is non-matched)"];
        } else if (nRet == 20) {
            initStr = [initStr stringByAppendingString:@"(Product is not supported)"];
        } else if (nRet == 21) {
            initStr = [initStr stringByAppendingString:@"(Do not use simulator)"];
        }else if (nRet == 29) {
            initStr = [initStr stringByAppendingString:@"(lic type error)"];
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            UIAlertView *alertV = [[UIAlertView alloc]initWithTitle:@"Tips" message:initStr delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
            [alertV show];
        });
        
        
    } else {
        //成功
        NSInteger day = [self calculateTheRemainingDaysOfLicenceWithDeadLine:self.sPlate.nsEndTime];
        
        if (day <= 15 && day != -1) {
            NSLog(@"⚠️授权还有不到15天到期❗️❗️❗️请及时更换");
        }
        
        
    }
    return nRet;
}

- (NSInteger)calculateTheRemainingDaysOfLicenceWithDeadLine:(NSString *)deadLine {
    if (!deadLine) {
        NSLog(@"deadline is nil");
        return -1;
    }
    //按照日期格式创建日期格式句柄
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSTimeZone *localTimeZone = [NSTimeZone localTimeZone];
    [dateFormatter setTimeZone:localTimeZone];
    //将日期字符串转换成Date类型
    
    NSDate *startDate = [NSDate date];
    NSDate *endDate = [dateFormatter dateFromString:deadLine];
    //将日期转换成时间戳
    NSTimeInterval start = [startDate timeIntervalSince1970]*1;
    NSTimeInterval end = [endDate timeIntervalSince1970]*1;
    NSTimeInterval value = end - start;
    NSInteger day = (NSInteger)value / (24 * 3600);
    return day + 1;
}

//MARK:图片方向修复
- (UIImage *)fixOrientation:(UIImage *)aImage {
    
    // No-op if the orientation is already correct
    if (aImage.imageOrientation == UIImageOrientationUp)
        return aImage;
    
    // We need to calculate the proper transformation to make the image upright.
    // We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
    CGAffineTransform transform = CGAffineTransformIdentity;
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, aImage.size.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
            
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;
            
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, aImage.size.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
        default:
            break;
    }
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
            
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.height, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
        default:
            break;
    }
    
    // Now we draw the underlying CGImage into a new context, applying the transform
    // calculated above.
    CGContextRef ctx = CGBitmapContextCreate(NULL, aImage.size.width, aImage.size.height,
                                             CGImageGetBitsPerComponent(aImage.CGImage), 0,
                                             CGImageGetColorSpace(aImage.CGImage),
                                             CGImageGetBitmapInfo(aImage.CGImage));
    CGContextConcatCTM(ctx, transform);
    switch (aImage.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            // Grr...
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.height,aImage.size.width), aImage.CGImage);
            break;
            
        default:
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.width,aImage.size.height), aImage.CGImage);
            break;
    }
    
    // And now we just create a new UIImage from the drawing context
    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
    UIImage *img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
    return img;
}



#pragma mark - lazy load
- (SPlate *)sPlate {
    if (!_sPlate) {
        _sPlate = [[SPlate alloc] init];
        _sPlate.needPlateLog = YES;
    }
    return _sPlate;
}

- (NSString *)codeVersion {
    return @"V20250211";
}

- (NSString *)sdkVersion {
    return self.sPlate.sdkVersion;
}

@end
